<template>
  <el-row class="login-container" justify="center" align="middle">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="" />
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handelChange">{{
          formType ? "返回登录" : "注册账号"
        }}</el-link>
      </div>
      <el-form
        :model="Loginform"
        label-width="auto"
        style="max-width: 600px"
        :rules="rules"
        ref="loginFormRef"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="Loginform.userName"
            placeholder="手机号"
            prefix-icon="UserFilled"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="Loginform.passWord"
            placeholder="密码"
            prefix-icon="Lock"
            type="password"
          />
        </el-form-item>
        <el-form-item prop="validCode">
          <el-input
            v-model="Loginform.validCode"
            placeholder="验证码"
            prefix-icon="Lock"
            v-if="formType"
          >
            <template #append>
              <span @click="countdownChange">{{ countdown.validText }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :style="{ width: '100%' }"
            @click="submitForm(loginFormRef)"
          >
            {{ formType ? "注册账号" : "登录" }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import "element-plus/es/components/message/style/css";
import { ElMessage } from "element-plus";
import { computed, ref, toRaw } from "vue";
import { getCode, Login, useraUthentication, UserPermission } from "@/api";
import { useRouter } from "vue-router";
import UseuserPermission from "@/stores/UserPermission";
const userPermission = UseuserPermission();
const routerList = computed(() => userPermission.routerList);
const router = useRouter();
const imgUrl = new URL("../../../public/login-head.png", import.meta.url).href;
const formType = ref(0);
const Loginform = ref({
  userName: "",
  passWord: "",
  validCode: 1234,
});
const countdown = ref({
  validText: "获取验证码",
  time: 60,
});
const flag = ref(false);
const countdownChange = async () => {

  if (flag.value) return;
  console.log(1);
  const phoneReg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  if (!Loginform.value.userName || !phoneReg.test(Loginform.value.userName)) {
    return ElMessage({
      message: "请检查手机号是否正确",
      type: "warning",
    });
  }
  const timer = setInterval(() => {
    if (countdown.value.time <= 0) {
      countdown.value.time == 60;
      countdown.value.validText = "获取验证码";
      clearInterval(timer);
      flag.value=false
    } else {
      countdown.value.time -= 1;
      countdown.value.validText = `剩余${countdown.value.time}s`;
      console.log(1);
    }
  }, 1000);

  const resCode = await getCode({ tel: Loginform.value.userName });
  if (resCode.data.code === 10000) {
    ElMessage.success("发送成功");
    flag.value = true;
  }
};

const handelChange = () => {
  formType.value = formType.value ? 0 : 1;
};
const validateUser = (rules, value, callback) => {
  if (value === "") {
    callback(new Error("请输入账号"));
  } else {
    const phoneReg =
      /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    phoneReg.test(value)
      ? callback()
      : callback(new Error("手机号格式不正确，请输入正确手机号"));
  }
};
const validatePass = (rules, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    const passReg = /^[a-zA-Z0-9_-]{4,16}$/;
    passReg.test(value)
      ? callback()
      : callback("密码格式不对,需要4-16位字符,请确认格式");
  }
};
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log(Loginform.value);
      //注册页面
      if (formType.value) {
        const res = await useraUthentication(Loginform.value);
        console.log(res);

        if (res.data.code === 10000) {
          ElMessage.success("注册成功,请登录");
          formType.value = 0;
        }
      } else {
        const res = await Login(Loginform.value);
        console.log(res);
        if (res.data.code === 10000) {
          router.push("/");
          ElMessage.success("登录成功");
  
          //将token和用户信息缓存在浏览器
          localStorage.setItem("pz_token", res.data.data.token);
          localStorage.setItem(
            "pz_userInfo",
            JSON.stringify(res.data.data.userInfo)
          );
          UserPermission().then(({ data }) => {
            console.log(data.data);
            userPermission.dynamicMenu(data.data);
            console.log(routerList.value);
            toRaw(routerList.value).forEach((item) => {
              console.log(item);
              
              router.addRoute("main", item);
            });
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const rules = ref({
  userName: [
    {
      validator: validateUser,
      trigger: "blur",
    },
  ],
  passWord: [
    {
      validator: validatePass,
      trigger: "blur",
    },
  ],
});
const loginFormRef = ref();
</script>

<style scoped lang="less">
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;
  .card-header {
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>
